<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        body {
            width: 100%;
            height: 100vh;
            position: relative;
            background: rgb(192, 157, 157);
        }

        #canvas {
            position: absolute;
            top: 0;
            left: 0;
            background-color: white;
        }
    </style>
</head>

<body>
    <canvas id="canvas" width="600" height="600"></canvas>
    <script>
        // 定义一个笔的状态开关
        let painting = false
        // 存储老的位置
        let oldPoint = { x: undefined, y: undefined }
        // 存储新的位置
        let newPoint = { x: undefined, y: undefined }

        // canvas的上下文
        const canvas = document.getElementById("canvas")
        const ctx = canvas.getContext("2d")
        // 起笔
        canvas.onmousedown = e => {
            let x = e.x;
            let y = e.y;
            oldPoint = { x: x, y: y }
            painting = true;
        }
        // 画画
        canvas.onmousemove = e => {
            let x = e.x;
            let y = e.y;
            newPoint = { x: x, y: y }
            if (painting) {
                line(oldPoint.x, oldPoint.y, newPoint.x, newPoint.y) // 画画函数
                oldPoint = newPoint // 更新位置
            }
        }
        // 停笔
        canvas.onmouseup = () => {
            painting = false;
        };

        function line(xOld, yOld, xNew, yNew) {
            ctx.beginPath();
            ctx.lineWidth = 2;
            ctx.moveTo(xOld, yOld);
            ctx.lineTo(xNew, yNew);
            ctx.stroke();
            ctx.closePath();
        }
    </script>
</body>

</html>
